#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LangGraph 实用示例
这个示例是经过简化的，可以直接运行，不需要复杂的API配置
"""

import os
from typing import Dict, Any
from langchain_core.tools import tool
import datetime
import re

# 定义工具函数
@tool
def get_weather(city: str) -> str:
    """获取指定城市的天气信息"""
    weather_data = {
        "北京": "晴天，温度25°C，湿度60%，风速3m/s",
        "上海": "多云，温度22°C，湿度70%，风速2m/s", 
        "广州": "雨天，温度28°C，湿度85%，风速1m/s",
        "深圳": "晴天，温度30°C，湿度65%，风速2m/s",
        "杭州": "阴天，温度20°C，湿度75%，风速1m/s",
        "成都": "多云，温度24°C，湿度68%，风速2m/s",
        "西安": "晴天，温度26°C，湿度55%，风速3m/s",
        "武汉": "多云，温度23°C，湿度72%，风速2m/s",
        "重庆": "雨天，温度27°C，湿度80%，风速1m/s",
        "天津": "晴天，温度24°C，湿度58%，风速2m/s"
    }
    result = weather_data.get(city, f"{city}的天气：晴天，温度适宜，湿度正常")
    return result

@tool
def get_time_info() -> str:
    """获取当前时间信息"""
    now = datetime.datetime.now()
    weekday = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"][now.weekday()]
    return f"当前时间：{now.strftime('%Y年%m月%d日')} {weekday} {now.strftime('%H:%M:%S')}"

@tool
def calculate_math(expression: str) -> str:
    """计算数学表达式"""
    try:
        # 安全的数学计算
        allowed_chars = set('0123456789+-*/.() ')
        if not all(c in allowed_chars for c in expression):
            return "错误：只支持基本的数学运算符（+, -, *, /, ()）"
        
        # 简单的安全检查
        if 'import' in expression or 'exec' in expression or 'eval' in expression:
            return "错误：不支持的操作"
        
        result = eval(expression)
        return f"计算结果：{expression} = {result}"
    except Exception as e:
        return f"计算错误：{str(e)}"

@tool
def get_city_info(city: str) -> str:
    """获取城市基本信息"""
    city_info = {
        "北京": "中国首都，人口约2200万，著名景点：故宫、长城、天坛",
        "上海": "中国经济中心，人口约2400万，著名景点：外滩、东方明珠、豫园",
        "广州": "广东省省会，人口约1500万，著名景点：广州塔、陈家祠、白云山",
        "深圳": "经济特区，人口约1300万，著名景点：世界之窗、深圳湾公园、大梅沙",
        "杭州": "浙江省省会，人口约1200万，著名景点：西湖、灵隐寺、钱塘江",
        "成都": "四川省省会，人口约2100万，著名景点：宽窄巷子、大熊猫基地、武侯祠"
    }
    return city_info.get(city, f"抱歉，我还没有{city}的详细信息")

class SmartAgent:
    """智能助手类 - 模拟LangGraph的Agent行为"""
    
    def __init__(self):
        self.tools = {
            "get_weather": get_weather,
            "get_time_info": get_time_info,
            "calculate_math": calculate_math,
            "get_city_info": get_city_info
        }
        self.conversation_history = []
        
    def _analyze_input(self, user_input: str) -> Dict[str, Any]:
        """分析用户输入，决定使用哪个工具"""
        user_input_lower = user_input.lower()
        
        # 天气询问
        if any(word in user_input_lower for word in ["天气", "weather", "温度", "下雨", "晴天", "阴天", "多云"]):
            cities = ["北京", "上海", "广州", "深圳", "杭州", "成都", "西安", "武汉", "重庆", "天津"]
            for city in cities:
                if city in user_input:
                    return {"tool": "get_weather", "params": {"city": city}}
            return {"tool": "get_weather", "params": {"city": "北京"}}
        
        # 时间询问
        elif any(word in user_input_lower for word in ["时间", "几点", "现在", "time", "日期", "今天"]):
            return {"tool": "get_time_info", "params": {}}
        
        # 数学计算
        elif any(word in user_input_lower for word in ["计算", "算", "等于"]) or any(char in user_input for char in "+-*/="):
            # 提取数学表达式
            math_pattern = r'[\d+\-*/\.\(\)\s]+'
            match = re.search(math_pattern, user_input)
            if match:
                expression = match.group().strip()
                return {"tool": "calculate_math", "params": {"expression": expression}}
            return {"tool": "calculate_math", "params": {"expression": user_input}}
        
        # 城市信息
        elif any(word in user_input_lower for word in ["城市", "地方", "景点", "信息", "介绍"]):
            cities = ["北京", "上海", "广州", "深圳", "杭州", "成都"]
            for city in cities:
                if city in user_input:
                    return {"tool": "get_city_info", "params": {"city": city}}
            return {"tool": "get_city_info", "params": {"city": "北京"}}
        
        return {"tool": "chat", "params": {}}
    
    def _execute_tool(self, tool_name: str, params: Dict[str, Any]) -> str:
        """执行工具函数"""
        if tool_name in self.tools:
            try:
                tool_func = self.tools[tool_name]
                return tool_func.invoke(params)
            except Exception as e:
                return f"工具执行错误：{str(e)}"
        else:
            return "未知的工具"
    
    def _generate_response(self, user_input: str, tool_result: str, tool_name: str) -> str:
        """生成最终回复"""
        if tool_name == "chat":
            return ("🤖 我是一个智能助手，可以帮您：\n"
                    "1. 查询天气：'北京天气怎么样？'\n"
                    "2. 查询时间：'现在几点？'\n"
                    "3. 数学计算：'计算 2+3*4'\n"
                    "4. 城市信息：'介绍一下上海'\n"
                    "请告诉我您需要什么帮助！")
        
        # 根据工具类型生成不同的回复
        response_templates = {
            "get_weather": "🌤️ 天气查询结果：\n{result}",
            "get_time_info": "⏰ 时间信息：\n{result}",
            "calculate_math": "🔢 计算结果：\n{result}",
            "get_city_info": "🏙️ 城市信息：\n{result}"
        }
        
        template = response_templates.get(tool_name, "查询结果：\n{result}")
        return template.format(result=tool_result)
    
    def chat(self, user_input: str) -> str:
        """主要的对话函数"""
        # 1. 分析用户输入
        analysis = self._analyze_input(user_input)
        tool_name = analysis["tool"]
        params = analysis["params"]
        
        # 2. 执行工具或生成回复
        if tool_name == "chat":
            response = self._generate_response(user_input, "", tool_name)
        else:
            tool_result = self._execute_tool(tool_name, params)
            response = self._generate_response(user_input, tool_result, tool_name)
        
        # 3. 记录对话历史
        self.conversation_history.append({
            "user": user_input,
            "assistant": response,
            "tool_used": tool_name
        })
        
        return response
    
    def get_conversation_history(self) -> list:
        """获取对话历史"""
        return self.conversation_history

def demo_run():
    """运行演示"""
    print("=" * 60)
    print("🤖 LangGraph 智能助手演示")
    print("=" * 60)
    print("这是一个模拟LangGraph Agent行为的简化示例")
    print("\n支持的功能：")
    print("1. 天气查询：'北京天气怎么样？'")
    print("2. 时间查询：'现在几点？'")
    print("3. 数学计算：'计算 15 + 25 * 2'")
    print("4. 城市信息：'介绍一下上海'")
    print("5. 输入 'quit' 或 'exit' 退出")
    print("=" * 60)
    
    agent = SmartAgent()
    
    # 演示示例
    print("\n📝 自动演示：")
    demo_questions = [
        "上海天气怎么样？",
        "现在几点了？",
        "计算 12 * 8 + 5",
        "介绍一下杭州"
    ]
    
    for question in demo_questions:
        print(f"\n问题：{question}")
        answer = agent.chat(question)
        print(f"回答：{answer}")
        print("-" * 40)
    
    print("\n🎯 现在您可以开始提问了！")
    
    # 交互式对话
    while True:
        try:
            user_input = input("\n您的问题：").strip()
            
            if user_input.lower() in ['quit', 'exit', '退出', 'bye', 'q']:
                print("👋 再见！感谢使用智能助手！")
                break
            
            if not user_input:
                print("请输入有效的问题。")
                continue
            
            response = agent.chat(user_input)
            print(f"🤖 助手：{response}")
            
        except KeyboardInterrupt:
            print("\n\n👋 程序已终止。再见！")
            break
        except Exception as e:
            print(f"❌ 发生错误：{str(e)}")
            print("请重试...")

def main():
    """主函数"""
    print("LangGraph 学习示例启动...")
    print("这个示例展示了Agent的基本工作原理：")
    print("1. 分析用户输入")
    print("2. 选择合适的工具")
    print("3. 执行工具并生成回复")
    print("4. 记录对话历史")
    print("\n" + "="*50)
    
    demo_run()

if __name__ == "__main__":
    main() 